{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a18e5c3b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sat Dec 30 08:52:01 2023       \n",
      "+-----------------------------------------------------------------------------+\n",
      "| NVIDIA-SMI 525.85.12    Driver Version: 525.85.12    CUDA Version: 12.0     |\n",
      "|-------------------------------+----------------------+----------------------+\n",
      "| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\n",
      "| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\n",
      "|                               |                      |               MIG M. |\n",
      "|===============================+======================+======================|\n",
      "|   0  NVIDIA A100-SXM...  On   | 00000001:00:00.0 Off |                    0 |\n",
      "| N/A   32C    P0    70W / 400W |      0MiB / 81920MiB |      0%      Default |\n",
      "|                               |                      |             Disabled |\n",
      "+-------------------------------+----------------------+----------------------+\n",
      "|   1  NVIDIA A100-SXM...  On   | 00000002:00:00.0 Off |                    0 |\n",
      "| N/A   31C    P0    61W / 400W |      0MiB / 81920MiB |      0%      Default |\n",
      "|                               |                      |             Disabled |\n",
      "+-------------------------------+----------------------+----------------------+\n",
      "|   2  NVIDIA A100-SXM...  On   | 00000003:00:00.0 Off |                    0 |\n",
      "| N/A   32C    P0    63W / 400W |      0MiB / 81920MiB |      0%      Default |\n",
      "|                               |                      |             Disabled |\n",
      "+-------------------------------+----------------------+----------------------+\n",
      "|   3  NVIDIA A100-SXM...  On   | 00000004:00:00.0 Off |                    0 |\n",
      "| N/A   32C    P0    63W / 400W |      0MiB / 81920MiB |      0%      Default |\n",
      "|                               |                      |             Disabled |\n",
      "+-------------------------------+----------------------+----------------------+\n",
      "|   4  NVIDIA A100-SXM...  On   | 0000000B:00:00.0 Off |                    0 |\n",
      "| N/A   33C    P0    64W / 400W |      0MiB / 81920MiB |      0%      Default |\n",
      "|                               |                      |             Disabled |\n",
      "+-------------------------------+----------------------+----------------------+\n",
      "|   5  NVIDIA A100-SXM...  On   | 0000000C:00:00.0 Off |                    0 |\n",
      "| N/A   31C    P0    63W / 400W |      0MiB / 81920MiB |      0%      Default |\n",
      "|                               |                      |             Disabled |\n",
      "+-------------------------------+----------------------+----------------------+\n",
      "|   6  NVIDIA A100-SXM...  On   | 0000000D:00:00.0 Off |                    0 |\n",
      "| N/A   32C    P0    66W / 400W |      0MiB / 81920MiB |      0%      Default |\n",
      "|                               |                      |             Disabled |\n",
      "+-------------------------------+----------------------+----------------------+\n",
      "|   7  NVIDIA A100-SXM...  On   | 0000000E:00:00.0 Off |                    0 |\n",
      "| N/A   32C    P0    62W / 400W |      0MiB / 81920MiB |      0%      Default |\n",
      "|                               |                      |             Disabled |\n",
      "+-------------------------------+----------------------+----------------------+\n",
      "                                                                               \n",
      "+-----------------------------------------------------------------------------+\n",
      "| Processes:                                                                  |\n",
      "|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |\n",
      "|        ID   ID                                                   Usage      |\n",
      "|=============================================================================|\n",
      "|  No running processes found                                                 |\n",
      "+-----------------------------------------------------------------------------+\n"
     ]
    }
   ],
   "source": [
    "!nvidia-smi"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "fa20b683",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig\n",
    "import torch\n",
    "import json\n",
    "from peft import PeftModel\n",
    "\n",
    "TORCH_DTYPE = 'bfloat16'\n",
    "nf4_config = BitsAndBytesConfig(\n",
    "    load_in_4bit=True,\n",
    "    bnb_4bit_quant_type='nf4',\n",
    "    bnb_4bit_use_double_quant=True,\n",
    "    bnb_4bit_compute_dtype=getattr(torch, TORCH_DTYPE)\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c8f424e6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'mixtral-deepspeed/checkpoint-2320'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from transformers.trainer_utils import get_last_checkpoint\n",
    "\n",
    "latest = get_last_checkpoint(\"mixtral-deepspeed\")\n",
    "latest"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "35c85e90",
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained(latest)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "a8bb210c",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "The model was loaded with use_flash_attention_2=True, which is deprecated and may be removed in a future release. Please use `attn_implementation=\"flash_attention_2\"` instead.\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "3cae483668614960a40a3d488cfcff1c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading checkpoint shards:   0%|          | 0/19 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "base_model = AutoModelForCausalLM.from_pretrained(\n",
    "    'mistralai/Mixtral-8x7B-Instruct-v0.1',\n",
    "    use_flash_attention_2 = True,\n",
    "    quantization_config = nf4_config\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "de6cb4f0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "PeftModelForCausalLM(\n",
       "  (base_model): LoraModel(\n",
       "    (model): MixtralForCausalLM(\n",
       "      (model): MixtralModel(\n",
       "        (embed_tokens): Embedding(32000, 4096)\n",
       "        (layers): ModuleList(\n",
       "          (0-31): 32 x MixtralDecoderLayer(\n",
       "            (self_attn): MixtralFlashAttention2(\n",
       "              (q_proj): lora.Linear4bit(\n",
       "                (base_layer): Linear4bit(in_features=4096, out_features=4096, bias=False)\n",
       "                (lora_dropout): ModuleDict(\n",
       "                  (default): Dropout(p=0.1, inplace=False)\n",
       "                )\n",
       "                (lora_A): ModuleDict(\n",
       "                  (default): Linear(in_features=4096, out_features=32, bias=False)\n",
       "                )\n",
       "                (lora_B): ModuleDict(\n",
       "                  (default): Linear(in_features=32, out_features=4096, bias=False)\n",
       "                )\n",
       "                (lora_embedding_A): ParameterDict()\n",
       "                (lora_embedding_B): ParameterDict()\n",
       "              )\n",
       "              (k_proj): lora.Linear4bit(\n",
       "                (base_layer): Linear4bit(in_features=4096, out_features=1024, bias=False)\n",
       "                (lora_dropout): ModuleDict(\n",
       "                  (default): Dropout(p=0.1, inplace=False)\n",
       "                )\n",
       "                (lora_A): ModuleDict(\n",
       "                  (default): Linear(in_features=4096, out_features=32, bias=False)\n",
       "                )\n",
       "                (lora_B): ModuleDict(\n",
       "                  (default): Linear(in_features=32, out_features=1024, bias=False)\n",
       "                )\n",
       "                (lora_embedding_A): ParameterDict()\n",
       "                (lora_embedding_B): ParameterDict()\n",
       "              )\n",
       "              (v_proj): lora.Linear4bit(\n",
       "                (base_layer): Linear4bit(in_features=4096, out_features=1024, bias=False)\n",
       "                (lora_dropout): ModuleDict(\n",
       "                  (default): Dropout(p=0.1, inplace=False)\n",
       "                )\n",
       "                (lora_A): ModuleDict(\n",
       "                  (default): Linear(in_features=4096, out_features=32, bias=False)\n",
       "                )\n",
       "                (lora_B): ModuleDict(\n",
       "                  (default): Linear(in_features=32, out_features=1024, bias=False)\n",
       "                )\n",
       "                (lora_embedding_A): ParameterDict()\n",
       "                (lora_embedding_B): ParameterDict()\n",
       "              )\n",
       "              (o_proj): lora.Linear4bit(\n",
       "                (base_layer): Linear4bit(in_features=4096, out_features=4096, bias=False)\n",
       "                (lora_dropout): ModuleDict(\n",
       "                  (default): Dropout(p=0.1, inplace=False)\n",
       "                )\n",
       "                (lora_A): ModuleDict(\n",
       "                  (default): Linear(in_features=4096, out_features=32, bias=False)\n",
       "                )\n",
       "                (lora_B): ModuleDict(\n",
       "                  (default): Linear(in_features=32, out_features=4096, bias=False)\n",
       "                )\n",
       "                (lora_embedding_A): ParameterDict()\n",
       "                (lora_embedding_B): ParameterDict()\n",
       "              )\n",
       "              (rotary_emb): MixtralRotaryEmbedding()\n",
       "            )\n",
       "            (block_sparse_moe): MixtralSparseMoeBlock(\n",
       "              (gate): Linear4bit(in_features=4096, out_features=8, bias=False)\n",
       "              (experts): ModuleList(\n",
       "                (0-7): 8 x MixtralBLockSparseTop2MLP(\n",
       "                  (w1): Linear4bit(in_features=4096, out_features=14336, bias=False)\n",
       "                  (w2): Linear4bit(in_features=14336, out_features=4096, bias=False)\n",
       "                  (w3): Linear4bit(in_features=4096, out_features=14336, bias=False)\n",
       "                  (act_fn): SiLU()\n",
       "                )\n",
       "              )\n",
       "            )\n",
       "            (input_layernorm): MixtralRMSNorm()\n",
       "            (post_attention_layernorm): MixtralRMSNorm()\n",
       "          )\n",
       "        )\n",
       "        (norm): MixtralRMSNorm()\n",
       "      )\n",
       "      (lm_head): Linear(in_features=4096, out_features=32000, bias=False)\n",
       "    )\n",
       "  )\n",
       ")"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model = PeftModel.from_pretrained(base_model, latest)\n",
    "model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c5d091c4",
   "metadata": {},
   "outputs": [],
   "source": [
    "def parse_mistral_chat(messages, function_call = None):\n",
    "\n",
    "    user_query = messages[-1]['content']\n",
    "\n",
    "    users, assistants = [], []\n",
    "    for q in messages[:-1]:\n",
    "        if q['role'] == 'user':\n",
    "            users.append(q['content'])\n",
    "        elif q['role'] == 'assistant':\n",
    "            assistants.append(q['content'])\n",
    "\n",
    "    texts = ['<s>']\n",
    "    \n",
    "    if function_call:\n",
    "        fs = []\n",
    "        for f in function_call:\n",
    "            f = json.dumps(f, indent=4)\n",
    "            fs.append(f)\n",
    "        fs = '\\n\\n'.join(fs)\n",
    "        texts.append(f'\\n[FUNCTIONCALL]\\n{fs}\\n')\n",
    "        \n",
    "    for u, a in zip(users, assistants):\n",
    "        texts.append(f'[INST] {u.strip()} [/INST] {a.strip()}</s>')\n",
    "\n",
    "    texts.append(f'[INST] {user_query.strip()} [/INST]')\n",
    "    prompt = ''.join(texts).strip()\n",
    "    return prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "e39c3e89",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Setting `pad_token_id` to `eos_token_id`:2 for open-end generation.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<s> [INST] camne nak code sentiment analysis guna python3 [/INST] Untuk mengimplementasikan sentiment analysis menggunakan Python 3, anda boleh menggunakan beberapa pustaka yang tersedia seperti:\n",
      "\n",
      "1. `TextBlob`: Pustaka yang boleh digunakam untuk melakukan pelbagai analisis teks seperti analisis kesan semula jadi, pengenalan entiti, pengenalan jenis, dan lain-lain. Untuk melakukan sentiment analysis, and\n"
     ]
    }
   ],
   "source": [
    "s = \"\"\"\n",
    "camne nak code sentiment analysis guna python3\n",
    "\"\"\"\n",
    "\n",
    "messages = [\n",
    "    {'role': 'user', 'content': s.strip()},\n",
    "]\n",
    "prompt = parse_mistral_chat(messages)\n",
    "inputs = tokenizer([prompt], return_tensors='pt', add_special_tokens=False).to('cuda')\n",
    "generate_kwargs = dict(\n",
    "    inputs,\n",
    "    max_new_tokens=128,\n",
    "    top_p=0.95,\n",
    "    top_k=50,\n",
    "    temperature=0.9,\n",
    "    do_sample=True,\n",
    "    num_beams=1,\n",
    ")\n",
    "r = model.generate(**generate_kwargs)\n",
    "print(tokenizer.decode(r[0]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "4be6e535",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Setting `pad_token_id` to `eos_token_id`:2 for open-end generation.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<s> [INST] terjemah `tak suka awak` ke inggeris [/INST] I don't like you.</s>\n"
     ]
    }
   ],
   "source": [
    "s = \"\"\"\n",
    "terjemah `tak suka awak` ke inggeris\n",
    "\"\"\"\n",
    "\n",
    "messages = [\n",
    "    {'role': 'user', 'content': s.strip()},\n",
    "]\n",
    "prompt = parse_mistral_chat(messages)\n",
    "inputs = tokenizer([prompt], return_tensors='pt', add_special_tokens=False).to('cuda')\n",
    "generate_kwargs = dict(\n",
    "    inputs,\n",
    "    max_new_tokens=128,\n",
    "    top_p=0.95,\n",
    "    top_k=50,\n",
    "    temperature=0.9,\n",
    "    do_sample=True,\n",
    "    num_beams=1,\n",
    ")\n",
    "r = model.generate(**generate_kwargs)\n",
    "print(tokenizer.decode(r[0]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9bedf3b6",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
